package process

import (
	"github.com/shirou/gopsutil/net"
	"github.com/shirou/gopsutil/process"
	"packet_capture/bean"
)

func GetFileInfo(pid int32) (pf []process.OpenFilesStat) {
	newProcess, err := process.NewProcess(pid)
	if err == nil {
		files, _ := newProcess.OpenFiles()
		return files
	}
	return nil
}

func GetNetInfo(pid int32) (pc []net.ConnectionStat) {
	newProcess, err := process.NewProcess(pid)
	if err == nil {
		connections, _ := newProcess.Connections()
		return connections
	}
	return nil
}

func GetAllProcessInfo() (ps []*bean.ProcessInfo) {
	pids, _ := process.Pids()
	arr := make([]*bean.ProcessInfo, 0)
	for i := range pids {
		newProcess, err := process.NewProcess(pids[i])
		if err == nil {
			name, _ := newProcess.Name()
			percent, _ := newProcess.CPUPercent()
			time, _ := newProcess.CreateTime()
			info, _ := newProcess.MemoryInfo()
			files, _ := newProcess.OpenFiles()
			threads, _ := newProcess.Threads()
			connections, _ := newProcess.Connections()
			arr = append(arr, &bean.ProcessInfo{
				Pid:            newProcess.Pid,
				ProcessName:    name,
				CpuUse:         percent,
				CreateTime:     time,
				MemoryInfoStat: info,
				FileSize:       len(files),
				ThreadSize:     len(threads),
				NetConnSize:    len(connections),
			})
		}
	}
	return arr
}
